package com.programmercarl.backtracking;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * https://leetcode.cn/problems/non-decreasing-subsequences/
 * 非递减子序列
 * 两种方法均可
 *
 * @author yulongtian
 * @create 2025-01-12 10:30
 */
public class Test10 {
    public static void main(String[] args) {
        Test10 test10 = new Test10();
        System.out.println(test10.findSubsequences1(new int[]{4, 6, 7, 7, 4, 5, 8}));
    }

    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        bfs(nums, 0, res, path);
        return res;
    }

    public void bfs(int[] nums, int startIndex, List<List<Integer>> res, List<Integer> path) {
        if (path.size() > 1) {
            res.add(new ArrayList<>(path));
        }
        Set<Integer> set = new HashSet<>();
        for (int i = startIndex; i < nums.length; i++) {
            if (set.contains(nums[i]) || (!path.isEmpty() && nums[i] < path.get(path.size() - 1))) {
                continue;
            }
            set.add(nums[i]);
            path.add(nums[i]);
            bfs(nums, i + 1, res, path);
            path.remove(path.size() - 1);
        }
    }

    public List<List<Integer>> findSubsequences1(int[] nums) {
        Set<List<Integer>> resSet = new HashSet<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        for (int i = 0; i < nums.length - 1; i++) {
            path.add(nums[i]);
            used[i] = true;
            backTracking(nums, i + 1, resSet, path, used);
            used[i] = false;
            path.remove(path.size() - 1);
        }
        List<List<Integer>> res = new ArrayList<List<Integer>>(resSet);
        return res;
    }

    public void backTracking(int[] nums, int startIndex, Set<List<Integer>> resSet, List<Integer> path, boolean[] used) {
        for (int i = startIndex; i < nums.length; i++) {
            if (nums[i] < path.get(path.size() - 1)) {
                continue;
            }
            if (nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            resSet.add(new ArrayList<>(path));
            backTracking(nums, i + 1, resSet, path, used);
            used[i] = false;
            path.remove(path.size() - 1);
        }
    }

}
